//
//  TJMessageController.m
//  XWC
//
//  Created by Hello on 2022/10/24.
//

#import "HJMessageController.h"
#import "HJChatMessageTextCell.h"
#import "HJChatMessageVideoCell.h"
#import "HJChatMessageVoiceCell.h"
#import "HJChatMessageFileCell.h"
#import "HJChatMessageImageCell.h"
#import "HJChatMessageSystemCell.h"
#import "HJChatMessageModel.h"
#import "HJIM.h"
#import "TUIDefine.h"
#import "NSString+emoji.h"
#import "HJPopMenuController.h"

@interface HJMessageController ()<HJChatMessageCellDelegate>

@property (nonatomic, assign) NSInteger pageNumber;
@property (nonatomic, assign) NSInteger pageSize;

@property (nonatomic, assign) BOOL isLoadAllMessage;
@property (nonatomic, strong) HJChatMessageModel *lastMessageModel;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;
@property (nonatomic, strong) NSDictionary *menuDatas;
//搞个缓存池
@property (nonatomic, strong) NSMutableDictionary *userInfoPool;


@end

@implementation HJMessageController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pageNumber = 1;
    self.pageSize = 20;
    IQKeyboardManager.sharedManager.enable = NO;
    [self setUpTableView];
    [self loadMessageData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdateSendMessageStatusNotification:) name:updateSendMessageStatusNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleClearHistoryNotification:) name:clearHistoryNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleBeginSendMessageNotification:) name:beginSendMessageNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdateChatUserInfoNotification:) name:updateChatUserInfoNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdateOfflineConversationNotification:) name:updateOfflineConversationNotification object:nil];
}

- (void)setUpTableView {
    
    self.tableView.backgroundColor = UIColor.tj_F6F6F6Color;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.scrollsToTop = NO;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.tableView registerClass:HJChatMessageTextCell.class forCellReuseIdentifier:@"HJChatMessageTextCell"];
    [self.tableView registerClass:HJChatMessageVideoCell.class forCellReuseIdentifier:@"HJChatMessageVideoCell"];
    [self.tableView registerClass:HJChatMessageVoiceCell.class forCellReuseIdentifier:@"HJChatMessageVoiceCell"];
    [self.tableView registerClass:HJChatMessageFileCell.class forCellReuseIdentifier:@"HJChatMessageFileCell"];
    [self.tableView registerClass:HJChatMessageImageCell.class forCellReuseIdentifier:@"HJChatMessageImageCell"];
    [self.tableView registerClass:HJChatMessageSystemCell.class forCellReuseIdentifier:@"HJChatMessageSystemCell"];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapViewController)];
    tap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, TMessageController_Header_Height)];
    headerView.backgroundColor = UIColor.redColor;
    self.indicatorView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, TMessageController_Header_Height)];
    self.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    self.tableView.tableHeaderView = self.indicatorView;
    [self.indicatorView startAnimating];
}


- (void)handleUpdateOfflineConversationNotification:(NSNotification *)not {
    NSDictionary *dict = not.object;
    
    HJChatSessionModel *sessionModel = dict[@"sessionModel"];
    NSArray *messages = dict[@"messages"];
    
    if (![sessionModel.sessionId isEqualToString:self.sessionModel.sessionId]) return;
    
    if (sessionModel.isMute.boolValue) {
        sessionModel.muteMessageUnReadCount = @"0";
        [sessionModel bg_saveOrUpdate];
        [[NSNotificationCenter defaultCenter] postNotificationName:updateConversationInfoNotification object:sessionModel];
    } else {
        [HJIM.shareIM.userManager readMessageWithType:sessionModel.chatType sessionId:sessionModel.sessionId msgIds:nil begin:^{
            sessionModel.unReadCount = @"0";
            [sessionModel bg_saveOrUpdate];
            [HJIM.shareIM.conversationManager updateBadge];
            [[NSNotificationCenter defaultCenter] postNotificationName:updateConversationInfoNotification object:sessionModel];
        } completion:nil];
    }
    
    //消息合并
    NSMutableDictionary *messageDict = [NSMutableDictionary dictionary];
    for (HJChatMessageLayout *messageLayout in self.messageLayouts) {
        [messageDict setObject:messageLayout.messageModel forKey:messageLayout.messageModel.msgId];
    }
    
    for (HJChatMessageModel *messageModel in messages) {
        [messageDict setObject:messageModel forKey:messageModel.msgId];
    }
    
    //根据时间在内存中消息进行排序
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:NO];
    NSArray *itemsSortedArray = [messageDict.allValues sortedArrayUsingDescriptors:@[sortDescriptor]];
    
    NSMutableArray *messageLayouts = [NSMutableArray array];
    
    //计算布局
    self.lastMessageModel = nil;
    for (NSInteger i = itemsSortedArray.count - 1; i >= 0; i--) {
        
        HJChatMessageModel *messageModel = itemsSortedArray[i];
        HJChatMessageLayout *messageLayout = [HJChatMessageLayout messagelayoutWithMessageModel:messageModel];
        [messageLayout calculateLayoutWithModel:messageModel lastMessageTime:self.lastMessageModel.timestamp.integerValue];
        self.lastMessageModel = messageModel;
        [messageLayouts addObject:messageLayout];
    }
    
    dispatch_async_main_queue(^{
        
        [self.messageLayouts removeAllObjects];
        [self.messageLayouts addObjectsFromArray:messageLayouts];
        
        [self.tableView reloadData];
        [self.tableView layoutIfNeeded];
        [self scrollToBottom:NO];
    });
}

- (void)handleUpdateChatUserInfoNotification:(NSNotification *)not {
    HJChatUserModel *userModel = not.object;
    
    if (self.sessionModel.chatType == HJChatTypeSingle) return;
    
    dispatch_async_serial_queue(^{
        NSMutableArray *messageModels = [NSMutableArray array];
        for (HJChatMessageLayout *obj in self.messageLayouts) {
            
            if ([userModel.userId isEqualToString:obj.messageModel.senderId]) {
                
                HJChatUserModel *chatModel = [self queryUserInfoByUserId:userModel.userId];
                
                if (chatModel) {
                    BOOL isChange = NO;
                    if (chatModel.showName && ![obj.messageModel.senderNickname isEqualToString:chatModel.showName]) {
                        obj.messageModel.senderNickname = chatModel.showName;
                        
                        CGFloat nameW = [obj.messageModel.senderNickname getStringSizeWithWidth:200 fontSize:13].width + 10;
                        CGRect nameLabelRect = obj.nameLabelRect;
                        nameLabelRect.size.width = nameW;
                        obj.nameLabelRect = nameLabelRect;
                        isChange = YES;
                    }
                    
                    if (chatModel.avatar && ![obj.messageModel.senderAvatar isEqualToString:chatModel.avatar]) {
                        obj.messageModel.senderAvatar = chatModel.avatar;
                        isChange = YES;
                    }
                    
                    if (isChange) {
                        [messageModels addObject:obj.messageModel];
                    }
                }
            }
        }
        
        [HJChatMessageModel bg_saveOrUpdateArray:messageModels];
        dispatch_async_main_queue(^{
            [self.tableView reloadData];
        });
    });
    
}


- (void)handleClearHistoryNotification:(NSNotification *)not {
    NSString *sessionId = not.object;
    if ([sessionId isEqualToString:self.sessionModel.sessionId options:NSCaseInsensitiveSearch]) {
        [self.messageLayouts removeAllObjects];
        [self.tableView reloadData];
    }
}

- (void)handleUpdateSendMessageStatusNotification:(NSNotification *)not {
    HJChatMessageLayout *chatMessageLayout = [HJChatMessageLayout messagelayoutWithMessageModel:not.object];
    [self updateMessage:chatMessageLayout];
}

- (void)didTapViewController {
    if(self.delegate && [self.delegate respondsToSelector:@selector(didTapInMessageController:)]) {
        [self.delegate didTapInMessageController:self];
    }
}

- (NSMutableArray<HJChatMessageLayout *> *)messageLayouts {
    if (!_messageLayouts) {
        _messageLayouts = [NSMutableArray array];
    }
    return _messageLayouts;
}

- (void)scrollToBottom:(BOOL)animate {
    if (self.messageLayouts.count > 0) {
        NSInteger totalRow = [self.tableView numberOfRowsInSection:0];
        if (self.messageLayouts.count - 1 < totalRow) {
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messageLayouts.count - 1 inSection:0]
                                  atScrollPosition:UITableViewScrollPositionBottom
                                          animated:animate];
        } else {
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:totalRow - 1 inSection:0]
                                  atScrollPosition:UITableViewScrollPositionBottom
                                          animated:animate];
        }
        
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.messageLayouts.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJChatMessageLayout *messageLayout = self.messageLayouts[indexPath.row];
    
    HJChatMessageCell *cell = nil;
    if ([messageLayout.messageModel isTipMessage]) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"HJChatMessageSystemCell" forIndexPath:indexPath];
        cell.messageLayout = messageLayout;
        return cell;
    }
    
    if (messageLayout.messageModel.messageType == HJMessageTypeText) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"HJChatMessageTextCell" forIndexPath:indexPath];
    } else if (messageLayout.messageModel.messageType == HJMessageTypeImage) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"HJChatMessageImageCell" forIndexPath:indexPath];
    } else if (messageLayout.messageModel.messageType == HJMessageTypeVideo) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"HJChatMessageVideoCell" forIndexPath:indexPath];
    } else if (messageLayout.messageModel.messageType == HJMessageTypeVoice) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"HJChatMessageVoiceCell" forIndexPath:indexPath];
    } else if (messageLayout.messageModel.messageType == HJMessageTypeOther) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"HJChatMessageFileCell" forIndexPath:indexPath];
    }
    cell.messageLayout = messageLayout;
    cell.delegate = self;
    return cell ?: [HJChatMessageCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.messageLayouts[indexPath.row].cellHeight;
}

- (void)updateMessage:(HJChatMessageLayout *)messageLayout {
    dispatch_safe_queue(^{
        [self.messageLayouts enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(HJChatMessageLayout * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.messageModel.sessionId isEqualToString:messageLayout.messageModel.sessionId options:NSCaseInsensitiveSearch]) {
                if ([obj.messageModel.msgId isEqualToString:messageLayout.messageModel.msgId]) {
                    obj.messageModel.msgStatus = messageLayout.messageModel.msgStatus;
                    obj.messageModel.localPath = messageLayout.messageModel.localPath.lastPathComponent.tj_IMFileCachePath;
                    NSInteger totalRow = [self.tableView numberOfRowsInSection:0];
                    if (idx < totalRow) {
                        TJLog(@"reloadRowsAtIndexPaths idx = %ld, self.messageLayouts.count = %ld", idx, self.messageLayouts.count);
                        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:idx inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                    } else {
                        [self.tableView reloadData];
                    }
                    *stop = YES;
                }
            }
        }];
    });
}

//一种是群聊的, 一种是单聊的, 群里的时候都带有头像和名字, 不需要查询, 只需要更新这个用户,
- (void)addNewMessage:(HJChatMessageLayout *)messageLayout {//用户头像更新的话, 在用户查看资料后, 下次进来聊天界面就更新了, 不用及时更新,及时更新需要在看完资料后查看是否变化遍历所有的消息更新
    if (!TJIM_isSelf(messageLayout.messageModel.senderId)) {
        //不需要每次改了头像都全部更新, 在取出这个消息的时候本地查询下这个用户的信息就行了, 用户头像
        //如果能查到好友model,就一定能查到userModel
        
        HJChatUserModel *chatModel = [self queryUserInfoByUserId:messageLayout.messageModel.senderId];
        if (chatModel) {
            BOOL isChange = NO;
            if (chatModel.showName && ![messageLayout.messageModel.senderNickname isEqualToString:chatModel.showName]) {
                messageLayout.messageModel.senderNickname = chatModel.showName;
                isChange = YES;
            }
            
            if (chatModel.avatar && ![messageLayout.messageModel.senderAvatar isEqualToString:chatModel.avatar]) {
                messageLayout.messageModel.senderAvatar = chatModel.avatar;
                isChange = YES;
            }
            
            if (isChange) {
                [messageLayout.messageModel bg_saveOrUpdate];
            }
        }
    }
    [messageLayout calculateLayoutWithModel:messageLayout.messageModel lastMessageTime:self.messageLayouts.lastObject.messageModel.timestamp.integerValue];
    
    dispatch_async_main_queue(^{
        [self.messageLayouts addObject:messageLayout];
        NSInteger totalRow = [self.tableView numberOfRowsInSection:0];
        
        TJLog(@"insertRowsAtIndexPaths totalRow = %ld, self.messageLayouts.count = %ld", totalRow, self.messageLayouts.count);
        
        if (totalRow == self.messageLayouts.count-1) {
            TJLog(@"insertRowsAtIndexPaths");
            [UIView setAnimationsEnabled:NO];
            [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.messageLayouts.count - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            [UIView setAnimationsEnabled:YES];
        } else {
            [self.tableView reloadData];
        }
        [self scrollToBottom:NO];
    });
}

- (void)handleBeginSendMessageNotification:(NSNotification *)not {
    if (!not.object) return;
    HJChatMessageModel *messageModel = not.object;
    if ([messageModel.sessionId isEqualToString:self.sessionModel.sessionId options:NSCaseInsensitiveSearch]) {
        HJChatMessageLayout *messageLayout = [HJChatMessageLayout messagelayoutWithMessageModel:not.object];
        [self addNewMessage:messageLayout];
    }
}

- (void)chatMessageCell:(HJChatMessageCell *)cell longGesture:(HJChatCellLongTapType)longTapType {
    if (longTapType == HJChatCellLongTapTypeAvatar) {
        if ([self.delegate respondsToSelector:@selector(messageController:onLongSelectMessageAvatar:)]) {
            [self.delegate messageController:self onLongSelectMessageAvatar:cell];
        }
        return;
    }
    
    if (longTapType == HJChatCellLongTapTypeContentView) {
        
        NSMutableArray *types = [NSMutableArray array];
        if (cell.messageLayout.messageModel.messageType == HJMessageTypeText) {
            [types addObject:@(HJPopMenuTypeCopy)];
        }
        
        [types addObject:@(HJPopMenuTypeDelete)];
        
        HJPopMenuController *popMenuController = [[HJPopMenuController alloc] initWithTypes:types];
        TJWeakify(self)
        popMenuController.controllerName = NSStringFromClass(self.class);
        popMenuController.sourceRect = [cell convertRect:cell.containerView.frame toView:getMainWindow()];
        [popMenuController showInController:self];
        [popMenuController setDidSelectItemBlock:^(HJPopMenuType type) {
            if (type == HJPopMenuTypeCopy) {
                NSString *text = [cell.messageLayout.messageModel.content getLocalizableStringWithFaceContent];
                [HJTools copyStringToPasteboard:text];
                return;
            }
            
            if (type == HJPopMenuTypeDelete) {
                [weakself deleteMessage:cell.messageLayout];
                return;
            }
            
        }];
        return;
    }
}

- (void)chatMessageCell:(HJChatMessageCell *)cell tapGesture:(HJChatCellClickType)clickType {
    if (clickType == HJChatCellClickTypeAvatar) {
        if ([self.delegate respondsToSelector:@selector(messageController:onSelectMessageAvatar:)]) {
            [self.delegate messageController:self onSelectMessageAvatar:cell];
        }
    } else {
        if ([self.delegate respondsToSelector:@selector(messageController:onSelectMessageContent:)]) {
            [self.delegate messageController:self onSelectMessageContent:cell];
        }
    }
    
}

- (void)chatMessageCellDidClickRetryButton:(HJChatMessageCell *)cell {
    if ([self.delegate respondsToSelector:@selector(messageController:didClickRetryButton:)]) {
        [self.delegate messageController:self didClickRetryButton:cell];
    }
}

- (void)clearAllMessge {
    
}

- (void)deleteMessage:(HJChatMessageLayout *)messageLayout {
    
    dispatch_async_serial_queue(^{
        
        BOOL result = [HJIM.shareIM.messageManager deleteMessagesBySessionId:self.sessionModel.sessionId messageId:messageLayout.messageModel.msgId];
        if (result) {
            
            NSString *localPath = messageLayout.messageModel.localPath.lastPathComponent.tj_IMFileCachePath;
            if ([[NSFileManager defaultManager] fileExistsAtPath:localPath]) {
                [[NSFileManager defaultManager] removeItemAtPath:localPath error:nil];
            }
                        
            [HJIM.shareIM.conversationManager getConversationBySessionId:self.sessionModel.sessionId completion:^(HJChatSessionModel * _Nonnull sessionModel) {
                [[NSNotificationCenter defaultCenter] postNotificationName:updateConversationNotification object:sessionModel];
            }];
            
            NSInteger index = [self.messageLayouts indexOfObject:messageLayout];
            
            dispatch_async_main_queue(^{
                [self.messageLayouts removeObject:messageLayout];
                NSInteger totalRow = [self.tableView numberOfRowsInSection:0];
                if (index < totalRow) {
                    [UIView setAnimationsEnabled:NO];
                    [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                    [UIView setAnimationsEnabled:YES];
                } else {
                    [self.tableView reloadData];
                }
            });
        }
        
    });
    
    
}

- (void)loadMessageData {    
    
    self.pageNumber = 1;
    NSInteger currentTimestamp = [NSDate date].timestamp;
    [HJIM.shareIM.messageManager loadMessageDatasBySessionId:self.sessionModel.sessionId pageSize:self.pageSize pageNumber:self.pageNumber completion:^(NSArray * _Nonnull messages) {
                
        self.pageNumber++;
        
        NSMutableArray *messageLayouts = [NSMutableArray array];
        [messages enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(HJChatMessageModel *messageModel, NSUInteger idx, BOOL * _Nonnull stop) {
            if (!TJIM_isSelf(messageModel.senderId)) {
                
                HJChatUserModel *chatModel = [self queryUserInfoByUserId:messageModel.senderId];
                if (chatModel) {
                    BOOL isChange = NO;
                    if (chatModel.showName && ![messageModel.senderNickname isEqualToString:chatModel.showName]) {
                        messageModel.senderNickname = chatModel.showName;
                        isChange = YES;
                    }
                    
                    if (chatModel.avatar && ![messageModel.senderAvatar isEqualToString:chatModel.avatar]) {
                        messageModel.senderAvatar = chatModel.avatar;
                        isChange = YES;
                    }
                    
                    if (isChange) {
                        [messageModel bg_saveOrUpdate];
                    }
                }
            }
            
            HJChatMessageLayout *messageLayout = [HJChatMessageLayout messagelayoutWithMessageModel:messageModel];
            [messageLayout calculateLayoutWithModel:messageModel lastMessageTime:self.lastMessageModel.timestamp.integerValue];
            [messageLayouts addObject:messageLayout];
            
            if (messageLayout.messageModel.msgStatus == HJMessageStatusSending && (currentTimestamp - messageModel.timestamp.integerValue / 1000) > 180) {
                messageLayout.messageModel.msgStatus = HJMessageStatusFail;
                [messageLayout.messageModel bg_saveOrUpdate];
            }
            self.lastMessageModel = messageModel;
        }];
        
        
//        NSLog(@"messages = %@", messages);

        [self.messageLayouts removeAllObjects];
        [self.messageLayouts addObjectsFromArray:messageLayouts];
        
        dispatch_async_main_queue(^{
            
            if (messages.count < self.pageSize) {
                self.isLoadAllMessage = YES;
                [self.indicatorView stopAnimating];
                self.tableView.tableHeaderView.tj_height = 0;
            }
            [self.tableView reloadData];
            [self.tableView layoutIfNeeded];
            [self scrollToBottom:NO];
        });
    }];
}


- (void)loadMoreMessageData {
    
    NSInteger currentTimestamp = [NSDate date].timestamp;
    [HJIM.shareIM.messageManager loadMessageDatasBySessionId:self.sessionModel.sessionId pageSize:self.pageSize pageNumber:self.pageNumber completion:^(NSArray * _Nonnull messages) {
        
        self.pageNumber++;
        
        NSMutableArray *messageLayouts = [NSMutableArray array];
        __block CGFloat visibleHeight = 0;
        
        [messages enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(HJChatMessageModel *messageModel, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (!TJIM_isSelf(messageModel.senderId)) {
                HJChatUserModel *chatModel = [self queryUserInfoByUserId:messageModel.senderId];
                if (chatModel) {
                    BOOL isChange = NO;
                    if (chatModel.showName && ![messageModel.senderNickname isEqualToString:chatModel.showName]) {
                        messageModel.senderNickname = chatModel.showName;
                        isChange = YES;
                    }
                    
                    if (chatModel.avatar && ![messageModel.senderAvatar isEqualToString:chatModel.avatar]) {
                        messageModel.senderAvatar = chatModel.avatar;
                        isChange = YES;
                    }
                    
                    if (isChange) {
                        [messageModel bg_saveOrUpdate];
                    }
                }
            }
            HJChatMessageLayout *messageLayout = [HJChatMessageLayout messagelayoutWithMessageModel:messageModel];
            [messageLayout calculateLayoutWithModel:messageModel lastMessageTime:self.lastMessageModel.timestamp.integerValue];
            [messageLayouts addObject:messageLayout];
            visibleHeight += messageLayout.cellHeight;
            
            if (messageLayout.messageModel.msgStatus == HJMessageStatusSending && (currentTimestamp - messageModel.timestamp.integerValue / 1000) > 180) {
                messageLayout.messageModel.msgStatus = HJMessageStatusFail;
                [messageLayout.messageModel bg_saveOrUpdate];
            }
            self.lastMessageModel = messageModel;
        }];
        
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, messageLayouts.count)];
        [self.messageLayouts insertObjects:messageLayouts atIndexes:indexSet];
        
        dispatch_async_main_queue(^{
            
            [self.tableView layoutIfNeeded];
            [self.tableView reloadData];
            
            if (messages.count < self.pageSize) {
                self.isLoadAllMessage = YES;
            }
            
            if (self.isLoadAllMessage) {
                [self.indicatorView stopAnimating];
                self.tableView.tableHeaderView.tj_height = 10;
                visibleHeight -= TMessageController_Header_Height;
            }
            
            [self.tableView scrollRectToVisible:CGRectMake(0, self.tableView.contentOffset.y + visibleHeight, self.tableView.frame.size.width, self.tableView.frame.size.height) animated:NO];
        });
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y <= TMessageController_Header_Height
        && !_isLoadAllMessage) {
        [self loadMoreMessageData];
    }
}

- (HJChatMessageModel *)getFirstMessage {
    return self.messageLayouts.firstObject.messageModel;
}

- (NSDictionary *)menuDatas {
    if (!_menuDatas) {
        _menuDatas = @{
            @"forward": @{
                @"imageName": @"icon_forward",
                @"name": @"转发",
                @"buttonId": @1,
            },
            @"delete": @{
                @"imageName": @"icon_delete",
                @"name": @"删除",
                @"buttonId": @2,
            },
            @"backups": @{
                @"imageName": @"icon_imcopy",
                @"name": @"备份",
                @"buttonId": @3,
            },
            @"copy": @{
                @"imageName": @"icon_imcopy",
                @"name": @"复制",
                @"buttonId": @4,
            }
        };
    }
    return _menuDatas;
}

- (void)dealloc {
    TJLog(@"%s", __func__);
}

- (HJChatUserModel *)queryUserInfoByUserId:(NSString *)userId {
    HJChatUserModel *chatModel = [self.userInfoPool objectForKey:userId];
    if (chatModel) {
        return chatModel;
    }
    
    chatModel = [HJIM.shareIM.userManager queryUserInfoByUserId:userId];
    if (chatModel) {
        [self.userInfoPool setObject:chatModel forKey:userId];
        return chatModel;
    }
    return nil;
}

- (NSMutableDictionary *)userInfoPool {
    if (!_userInfoPool) {
        _userInfoPool = [NSMutableDictionary dictionary];
    }
    return _userInfoPool;
}

@end
